package com.cd.dao;

import com.cd.entity.Movie;
import com.cd.mapper.MovieMapper;
import com.cd.util.MybatisUtil;
import com.cd.util.PageResult;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.session.SqlSession;

import java.io.IOException;
import java.util.List;

public class MovieDao {

	// 1. 查询所有电影
	public List<Movie> findAll() throws IOException {
		try (SqlSession session = MybatisUtil.getSqlSession(true)) {
			MovieMapper mapper = session.getMapper(MovieMapper.class);
			return mapper.findAll();
		}
	}

	// 2. 分页查询
	public PageResult<Movie> findByPage(int page, int pageSize) throws IOException {
		// 2.1 开始分页
		PageHelper.startPage(page, pageSize);
		// 2.2 查询得到所有电影信息
		List<Movie> movies = findAll();
		// 2.3 将查询结果转换为Page<Movie>对象
		Page<Movie> pageMovies = (Page<Movie>) movies;
		// 2.4 最后返回构造的PageResult对象
		return new PageResult<>(pageMovies.getTotal(), pageMovies.getResult());
	}

	// 条件查询带分页
	public PageResult<Movie> search(int page, int pageSize, Movie movie) throws IOException {
		// 1. 开始分页
		PageHelper.startPage(page, pageSize);
		// 2. 开始分页查询
		try (SqlSession session = MybatisUtil.getSqlSession(true)) {
			MovieMapper mapper = session.getMapper(MovieMapper.class);
			// 修正：传递 Movie 对象
			List<Movie> movies = mapper.search(String.valueOf(movie));
			// 2.3 将查询结果转换为Page<Movie>对象
			Page<Movie> pageMovies = (Page<Movie>) movies;
			// 2.4 最后返回构造的PageResult对象
			return new PageResult<>(pageMovies.getTotal(), pageMovies.getResult());
		}
	}

	// 3. 添加电影
	public void add(Movie movie) throws IOException {
		try (SqlSession session = MybatisUtil.getSqlSession(true)) {
			MovieMapper mapper = session.getMapper(MovieMapper.class);
			mapper.add(movie);
		}
	}

	// 4. 修改电影
	public void update(Movie movie) throws IOException {
		try (SqlSession session = MybatisUtil.getSqlSession(true)) {
			MovieMapper mapper = session.getMapper(MovieMapper.class);
			mapper.update(movie);
		}
	}

	public void delete(String[] split) throws IOException {
		try (SqlSession session = MybatisUtil.getSqlSession(true)) {
			MovieMapper mapper = session.getMapper(MovieMapper.class);
			for (String s : split) {
				mapper.delete(Long.parseLong(s));
			}
		}
	}

	// 根据 ID 查询电影
	public int findById(Long movieId) throws IOException {
		try (SqlSession session = MybatisUtil.getSqlSession(true)) {
			MovieMapper mapper = session.getMapper(MovieMapper.class);
			// 调用 mapper 的 findById 方法查询电影
			return mapper.findById(movieId);
		}
	}
}